package com.ruoyi.controller;

import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.domain.Coach;
import com.ruoyi.service.ICoachService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.domain.User;
import com.ruoyi.service.IUserService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 学员Controller
 *
 * @author ruoyi
 * @date 2025-03-14
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private ICoachService coachService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询学员列表
     */
    @RequiresPermissions("user:user:list")
    @GetMapping("/list")
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出学员列表
     */
    @RequiresPermissions("user:user:export")
    @Log(title = "学员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user) {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "学员数据");
    }

    /**
     * 获取学员详细信息
     */
    @RequiresPermissions("user:user:query")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(userService.selectUserByUserId(userId));
    }

    /**
     * 新增学员
     */
    @RequiresPermissions("user:user:add")
    @Log(title = "学员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改学员
     */
    @RequiresPermissions("user:user:edit")
    @Log(title = "学员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user) {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除学员
     */
    @RequiresPermissions("user:user:remove")
    @Log(title = "学员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByUserIds(userIds));
    }

    @PostMapping("/login")
    public R<?> login(@RequestBody Map<String, String> map) {
        String userName = map.remove("userName");
        String userPassword = map.remove("userPassword");
        User user = userService.selectUserByUserName(userName);

        Coach coach = coachService.selectCoachByUserName(userName);
        if (user == null && coach == null) {
            throw new RuntimeException("用户名不存在");
        }
        if (user != null && user.getUserPassword().equals(userPassword)) {
            LoginUser loginUser = new LoginUser();
            SysUser sysUser = new SysUser();
            sysUser.setUserId(user.getUserId());
            sysUser.setUserName(user.getUserName());
            loginUser.setSysUser(sysUser);
            Map<String, Object> token = tokenService.createToken(loginUser);
            return R.ok(token);
        }
        if (coach != null && coach.getCoachPassword().equals(userPassword)) {
            LoginUser loginUser = new LoginUser();
            SysUser sysUser = new SysUser();
            sysUser.setUserId(coach.getCoachId());
            sysUser.setUserName(coach.getCoachName());
            loginUser.setSysUser(sysUser);
            Map<String, Object> token = tokenService.createToken(loginUser);
            return R.ok(token);
        }
        throw new RuntimeException("用户名或密码错误");
    }

    @PostMapping("selOne")
    public R<?> selOne(@RequestHeader("Authorization") String token) {
        Claims claims = JwtUtils.parseToken(token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY));
        String username = (String) claims.get("username");
        User user = userService.selectUserByUserName(username);
        return R.ok(user);
    }

    @PostMapping("update")
    public R<?> update(@RequestBody User user) {
        userService.updateUser(user);
        return R.ok();
    }

    @PostMapping("recharge")
    public R<?> recharge(@RequestBody Integer num,@RequestHeader("Authorization") String token) {
        Claims claims = JwtUtils.parseToken(token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY));
        String username = (String) claims.get("username");
        userService.recharge(num,username);
        return R.ok();
    }

    @PostMapping("pay")
    public R<?> pay(@RequestBody Integer num,@RequestHeader("Authorization") String token) {
        Claims claims = JwtUtils.parseToken(token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY));
        String username = (String) claims.get("username");
        userService.pay(num,username);
        return R.ok();
    }
}
